/*
 * ImportFromXML.java
 *
 * Created on 8. listopad 2006, 14:09
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package cz.results.winter6.io;

import cz.results.winter6.model.*;

import java.io.CharArrayWriter;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Trida pro import dat z XML souboru
 */
public class ImportFromXML extends DefaultHandler {
    
    private static StartSubjekt startSubjekt;
    
    private static String curElementName;                                       // nazev akt. elementu
    private MyCharArrayWriter curElementContent;                                // obsah akt. elementu
    
    private static Attributes curElementAttribs;                                // atributy akt. elementu
    private static int curJizda;                                                // cislo jizdy
    
    private static StartSubjektList tmpList = null;                             // list startovnich subjektu
    private static Boolean verbose = false;                                     // vypisovat info pri importu
    
    class MyCharArrayWriter extends CharArrayWriter {
        
        public Calendar toCalendar() {
            String tmpArr[] = this.toString().split(":",3);
            Calendar tmpCal =  new GregorianCalendar(1970,1,1,Integer.valueOf(tmpArr[0]),
                    Integer.valueOf(tmpArr[1]),Integer.valueOf(tmpArr[2]));
            return tmpCal;
        }
        
        public int toInt() {
            int tmpInt =  Integer.valueOf(this.toString());
            return tmpInt;
        }
               
    }
    
    
    /**
     * Importuje data o startovnich subjektech z XML souboru.
     * Format XML souboru muze obsahovat jak nacionale tak vysledky.
     * @param xmlFile pathname vstupniho XML souboru pro import
     * @return List<StartSubjekt> seznam Startovnich subjektu
     * @see definice formatu XML souboru
     */
    public static StartSubjektList doImportFromXML(String xmlFile) {
        
        try {
            File docFile = new File(xmlFile);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            ImportFromXML myHandler = new ImportFromXML();
            parser.parse(docFile, myHandler);
            return tmpList;
            
        } catch (Exception ex) {
            System.out.println(ex);
            return tmpList;
        }
    }
    
    
    /**
     * Vola se pri zacatku nacitani dokumentu
     * Vytvori prazdny seznam startovnich subjektu
     */
    public void startDocument() throws SAXException {
        tmpList = new StartSubjektList();                               // vytvoreni prazneho listu pro SS
        curElementContent = new MyCharArrayWriter();
        if (verbose) {
            System.out.println("ZACATEK DOKUMENTU");
        }
    }
    
    /**
     * Vola se pri ukonceni nacitani dokumentu
     */
    public void endDocument() throws SAXException {
        if (verbose) {
            System.out.println("");
            System.out.println("KONEC DOKUMENTU");
        }
    }
    
    
    /**
     * Vola se pri nacteni zacatku kazdeho elementu
     */
    public void startElement(String uri, String lName, String qName,
            Attributes attribs) throws SAXException {
        
        if (verbose) {
            System.out.println("");
            System.out.println("   ZACATEK " + qName);
            
            if (attribs.getLength() > 0) {
                for (int i = 0; i < attribs.getLength() ; i++) {
                    System.out.println("." + attribs.getQName(i) + "=" + attribs.getValue(i));
                }
            }
        }
        
        
        curElementName = qName;                                                 // ulozeni nazvu akt. elementu
        curElementContent.reset();                                              // inicializace bufferu pro ulozeni hodnoty akt. elementu
        curElementAttribs = attribs;                                            // ulozeni atributu akt. elementu
        
        
        if (qName == "ss") {
            tmpList.add(new StartSubjekt());                                    // prida novy objekt do seznamu pro SS
            
        } else if (curElementName == "priznaky") {
            
        } else if (qName == "jizda") {                                          // poslednimu SS v seznamu prida novou jizdu
            Jizda jizda = new Jizda();
            curJizda = Integer.valueOf(attribs.getValue("cislo"));
            tmpList.get(tmpList.size()-1).getJizdy().put(curJizda,jizda);
            
        }
    }
    
    /**
     * Vola se pri nacteni konce kazdeho elementu
     */
    public void endElement(String uri, String lName, String qName) throws SAXException {
        
        if (verbose) {
            System.out.println("   KONEC " + qName);
        }
        
        if (curElementContent != null && curElementContent.size() > 0) {
            
            if (curElementName == "nacionale") {
                Nacionale nacionale = new Nacionale(curElementContent.toString());
                tmpList.get(tmpList.size()-1).setNacionale(nacionale);
                
            } else if (curElementName == "priznak") {
                if (curElementAttribs.getValue("nazev") != null) {
                    Priznak priznak = new Priznak(curElementContent.toString());
                    tmpList.get(tmpList.size()-1).getPriznaky().put(curElementAttribs.getValue("nazev"),priznak);
                }
                
                
            } else if (curElementName == "casStartu") {
                Jizda tmpJizda = tmpList.get(tmpList.size()-1).getJizdy().get(curJizda);
                tmpJizda.setCasStartu(curElementContent.toCalendar());
                
            } else if (curElementName == "startovniPoradi") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).setPoradiStartu(curElementContent.toInt());
                
            } else if (curElementName == "stcZCasomiry") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).setStcZCasomiry(curElementContent.toInt());
                              
            } else if (curElementName == "status") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().setStatus(curElementContent.toInt());
                
            } else if (curElementName == "vysl") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().setVysledek(curElementContent.toInt());
                
            } else if (curElementName == "vyslText") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().setVysledekText(curElementContent.toString());
                               
            } else if (curElementName == "casStart") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().getVlCas().setDenniCasStart(curElementContent.toCalendar());
                
            } else if (curElementName == "casCil") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().getVlCas().setDenniCasCil(curElementContent.toCalendar());                
                
            } else if (curElementName == "casCisty") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().getVlCas().setCistyCas(curElementContent.toInt());                
                
            } else if (curElementName == "mezicasy") {
                
            } else if (curElementName == "mezicas") {
                
            } else if (curElementName == "penalizaceNaTrati") {
                
            } else if (curElementName == "soucet") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().getPenalizaceNaTrati().setSoucet(curElementContent.toInt());                                
                
            } else if (curElementName == "status") {
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().getPenalizaceNaTrati().setStatus(curElementContent.toInt());
                
            } else if (curElementName == "penalizace") {
                MistniPenalizace tmpPen = new MistniPenalizace(curElementContent.toInt(),Integer.valueOf(curElementAttribs.getValue("typ")));
                tmpList.get(tmpList.size()-1).getJizdy().get(curJizda).getVysledek().getPenalizaceNaTrati().put(curElementAttribs.getValue("nazev"),tmpPen);
                
            }
        }
    }
       
    
    /**
     * Vola se pri cteni hodnoty elementu
     */
    public void characters(char[] data, int start, int length) throws SAXException {
        StringBuffer buf = new StringBuffer(length);
        buf.append(data, start, length);
        
        if (buf.toString().trim().length() > 0) {
            if (verbose) {
                System.out.println("      " + buf);
            }
            String tmpStr = CSV2XML.zmensiPocetMezer(buf.toString());
            curElementContent.write(tmpStr, 0, tmpStr.length());
        }
    }
        
    
    /**
     * Vylistuje seznam
     */
    public static void listImport(List parList){
        System.out.println("LIST.....");
        for (Iterator i = parList.iterator(); i.hasNext();) {
            StartSubjekt startSubjekt = (StartSubjekt) i.next();

            System.out.println(startSubjekt.toXML());
        }
    }
    
    
    public static void main(String[] args) {
        
        StartSubjektList sl = doImportFromXML("/home/winter6/xmlImport1.xml");
        listImport(tmpList);
        
    }
    
    
}

